<?php
class Image {
	private $_aType = array (1 => 'gif', 2 => 'jpg', 3 => 'png', 4 => 'swf', 5 => 'psd', 6 => 'bmp', 7 => 'tiff', 8 => 'tiff', 9 => 'jpc', 10 => 'jp2', 11 => 'jpx', 12 => 'jb2', 13 => 'swc', 14 => 'iff', 15 => 'wbmp', 16 => 'xbm' );
	private $_aAllowType = array ('gif', 'jpg', 'png' );
	private $_rImg;
	private $_aInfo;
	
	public function setAllowType($aType) {
		$this->_aType = $aType;
	}
	
	public function open($sFile) {
		$aInfo = self::getInfo ( $sFile );
		
		if (is_array ( $aInfo )) {
			$this->_aInfo = $aInfo;
		} else {
			return false;
		}
		
		if (! in_array ( $aInfo ['type'], $this->_aAllowType )) {
			return false;
		}
		
		switch ($aInfo ['type']) {
			case 'gif' :
				$rImg = @imagecreatefromgif ( $sFile );
				break;
			case 'jpg' :
				$rImg = @imagecreatefromjpeg ( $sFile );
				break;
			case 'png' :
				$rImg = @imagecreatefrompng ( $sFile );
				break;
			default :
				return false;
		}
		
		if (! $rImg) {
			return false;
		} else {
			$this->_rImg = $rImg;
			return true;
		}
	
	}
	
	public function getInfo($sFile) {
		$aInfo = @getimagesize ( $sFile );
		if (is_array ( $aInfo )) {
			list ( $iWidth, $iHeight, $iType, $sAttr ) = $aInfo;
			return array ('width' => $iWidth, 'height' => $iHeight, 'type' => $this->_aType [$iType], 'attr' => $sAttr );
		} else {
			return false;
		}
	}
	
	public function resize($sFile, $iWidth = 0, $iHeight = 0, $bProportion = true) {
		if (! is_resource ( $this->_rImg )) {
			return false;
		}
		
		if ($bProportion) {
			if ($iWidth / $iHeight > $this->_aInfo ['width'] / $this->_aInfo ['height']) {
				$iWidth = $iHeight * $this->_aInfo ['width'] / $this->_aInfo ['height'];
			} else {
				$iHeight = $iWidth * $this->_aInfo ['height'] / $this->_aInfo ['width'];
			}
		}
		
		if ($iWidth >= $this->_aInfo ['width'] && $iHeight >= $this->_height) {
			$rImg = $this->_rImg;
		} else {
			$rImg = @imagecreatetruecolor ( $iWidth, $iHeight );
			if (! @imagecopyresampled ( $rImg, $this->_rImg, 0, 0, 0, 0, $iWidth, $iHeight, $this->_aInfo ['width'], $this->_aInfo ['height'] )) {
				return false;
			}
		}
		
		$sExt = strtolower ( substr ( $sFile, strrpos ( $sFile, '.' ) + 1 ) );
		switch ($sExt) {
			case 'gif' :
				$rRes = @imagegif ( $rImg, $sFile, 100 );
				break;
			case 'png' :
				$rRes = @imagepng ( $rImg, $sFile, 100 );
				break;
			default :
				$rRes = @imagejpeg ( $rImg, $sFile, 100 );
				break;
		}
		
		imagedestroy ( $rImg );
		if (! $rRes) {
			return false;
		} else {
			return true;
		}
	}
	
	public function getExif($sFile, $bSerialize = false) {
		try {
			if (! extension_loaded ( 'exif' )) {
				new ExceptionExt ( '模块exif没有安装' );
			}
		} catch ( ExceptionExt $e ) {
			$e->showError ();
		}
		
		$aData = @exif_read_data ( $sFile );
		if ($bSerialize) {
			return serialize ( $aData );
		} else {
			return $aData;
		}
	}
	
	public function close() {
		@imagedestroy ( $this->_rImg );
	}
}
?>